package com.example.test.controller;

import com.example.test.common.ResultBody;
import com.example.test.query.ActivitiUserQuery;
import com.github.pagehelper.PageInfo;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.activiti.engine.identity.UserQuery;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ：dengjue
 * @date ：Created in 2021/7/30 10:00
 * @description ：
 */
@Controller
@RequestMapping("/activiti/user")
public class ActivitiUserController {

    @Resource
    private IdentityService identityService;

    @RequestMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("/activitiUser");
        return mv;
    }

    @PostMapping("/save")
    @ResponseBody
    public ResultBody save(UserEntity userEntity){
        User user = identityService.createUserQuery().userId(userEntity.getId()).singleResult();
        if (user == null){
            identityService.saveUser(userEntity);
        }else{
           user.setFirstName(userEntity.getFirstName());
           user.setLastName(userEntity.getLastName());
           user.setEmail(userEntity.getEmail());
           user.setPassword(userEntity.getPassword());
           identityService.saveUser(user);
        }
        return ResultBody.success("用户保存成功!");
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public ResultBody delete(@RequestParam("id") String id){
        identityService.deleteUser(id);
        return ResultBody.success("用户删除成功!");
    }


    @GetMapping("/list")
    @ResponseBody
    public ResultBody<PageInfo<User>> list(ActivitiUserQuery userQuery){
        Integer offset = (userQuery.getPageNum() - 1) * userQuery.getPageSize();
        UserQuery userQuery1 = identityService.createUserQuery();
        if (!StringUtils.isEmpty(userQuery.getId())){
            userQuery1.userId(userQuery.getId());
        }
        if (!StringUtils.isEmpty(userQuery.getFirstName())){
            userQuery1.userFirstNameLike(userQuery.getFirstName());
        }
        List<User> userList = userQuery1.orderByUserId().asc().listPage(offset,userQuery.getPageSize());
        PageInfo<User> pageInfo = new PageInfo(userList);
        long total = userQuery1.count();
        pageInfo.setTotal(total);
        return ResultBody.success(pageInfo);
    }

}
